﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NetCore.BLL;
using NetCore.Model;

namespace NetCore.Mall.Admin.Web.Controllers
{
    [AllowAnonymous]
    public class LoginController : BaseController
    {
        public IUserService service { get; set; }
        // GET: Login
        public ActionResult Index(string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (!ModelState.IsValid)
            {
                return Content("数据有误~！请不要恶意禁用浏览器脚本~~~！");
            }
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(UserEntity model, bool rememberMe, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                string strError = "";
                string token = "";
                var result = service.Login(model.UserName, model.Password, ref strError,ref token);
                if (result != null)
                {
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name,result.UserName) ,
                        new Claim(ClaimTypes.MobilePhone,result.Phone),
                        new Claim(ClaimTypes.Email,result.Email) ,
                         new Claim(ClaimTypes.Authentication,token) ,
                        new Claim(ClaimTypes.NameIdentifier,result.UserId.ToString())

                    };
                    await SignInAsync(claims, result.UserId.ToString(), token, rememberMe);
                    // _logger.LogInformation(1, "User logged in.");
                    if (string.IsNullOrWhiteSpace(returnUrl))
                    {
                        return RedirectToAction("index", "home");
                    }
                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "用户名或者密码不正确！");
                    return View("Index", model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View("Index", model);
        }

    }
}